<?php
class BulkEmailsController extends NewslettersAppController {

	var $name = 'BulkEmails';
	var $helpers = array('Html', 'Form', 'Cms.Index', 'Javascript');
	var $components = array('Email', 'Session', 'Cms.Listener', 'Email');
	//var $uses = array();
	
	function beforeFilter()
	{
		$this->Listener->modelAlias = 'BulkEmail';
		parent::beforeFilter();
	}
	
	function admin_index()
	{
		$this->set('bulkEmails', $this->paginate());
	}
	
	function admin_prepareBulkEmail()
	{
		if(!empty($this->data))
		{
			extract($this->_getBulkActionParams());
			$count = count($ids);
			$this->set(compact('model', 'ids', 'count', 'plugin'));
			$this->data['BulkEmail']['model'] = $model;
			$this->data['BulkEmail']['ids'] = $rawIds;
			$this->data['BulkEmail']['plugin'] = $plugin;
		}
	}
	
	function admin_send()
	{
		if(!empty($this->data))
		{	
			if($this->BulkEmail->save($this->data))
			{
				//$threadId = $this->Thread->run('BulkEmailQueuesProcessor', array('id'=>$this->BulkEmail->id));
				$this->set('id', $this->BulkEmail->id);
				$this->infoMsg(__("Task scheduled."));
			}
		}
	}
	
	function cli_process()
	{
		$id = $this->params['id'];
		$email = $this->BulkEmail->findById($id);
		
		$model = $this->getModel($email['BulkEmail']['plugin'], $email['BulkEmail']['model']);
		$ids = explode(';', $email['BulkEmail']['ids']);
		$conditions = array('id'=>$ids);
		$records = $model->find('all', compact('conditions'));
		foreach($records as $record)
		{
			$this->prepareEmail();
			$this->Email->to = $record[$email['BulkEmail']['model']]['email'];
			$this->Email->sendAs = 'text';
			$this->Email->subject = Utility::replaceTemplateVars($email['BulkEmail']['subject'], $record[$email['BulkEmail']['model']]);
			$this->Email->send(Utility::replaceTemplateVars($email['BulkEmail']['body'], $record[$email['BulkEmail']['model']]));
			$this->Email->reset();
		}
		
		$this->BulkEmail->id = $id;
		$this->BulkEmail->saveField('status', 1);
	}
	
	function test2()
	{

		//$this->BulkEmail->save($bulkEmail);
	}
	
}
 ?>